#include "socket_gather_write.h"
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif
#include "socket_private_acl.h"
#include "socket_gather.h"
#include "pfunc.h"
#include "Log.h"
#ifdef __linux__
#include <stdexcept>
#endif

SocketGatherWrite::SocketGatherWrite(int _netType, SocketPrivate_ACL* socket_acl_,SocketGather *gsd_)
	: running(true)
	, netType(_netType)
	, socket_acl(socket_acl_)
	, gsd_ptr(gsd_)
{
}

SocketGatherWrite::~SocketGatherWrite(void)
{
	running = false;
}

void* SocketGatherWrite::run()
{
	if (NULL == socket_acl || NULL == gsd_ptr) 
	{
		CLogger::createInstance()->Log(MsgError,
			"SocketGatherWrite start fail for socket_acl or gsd_ptr is NULL,[%s %s %d]!"
			, __FILE__, __FUNCTION__, __LINE__);
		return 0;
	}
	while(running)
	{
		try {
			unsigned long _ipInt = 0;
			unsigned char buf[512] = { 0 };
			int len = gsd_ptr->getBuffer(_ipInt, buf);
			if (len > 0) 
			{
				// printf("getBuffer:\n");
				// for (int j = 0; j < len; j++) {
				// 	printf("%02X", buf[j]);
				// }
				// printf("\n");
				int ret = socket_acl->Write(_ipInt, (const char*)buf, len);
				if (ret <=0) 
				{
					//printf("send data: %d, buf %d\n",len,ret);
					CLogger::createInstance()->Log(MsgInfo,
						"SocketGatherWrite send data(%s,%d) fail. [%s %s %d]"
						,buf,len
						, __FILE__, __FUNCTION__, __LINE__);
				}
			}
		}
		catch (const std::exception& e)
		{
			CLogger::createInstance()->Log(MsgError,
				"SocketGatherWrite Run for data writing exception[%s],[%s %s %d]"
				, e.what()
				, __FILE__, __FUNCTION__, __LINE__);
		}
		catch (...) {
			CLogger::createInstance()->Log(MsgError,
				"SocketGatherWrite Run for data writing exception, [%s %s %d]!"
				, __FILE__, __FUNCTION__, __LINE__);
		}
		//检查有哪些链接,也可以放置读线程调用,写线程巡检链接持续性,读线程处理链接状态
		socket_acl->routClientLinkState();
		usleep(10);
	}
	return NULL;
};

